<?php

namespace app\command\babyTree;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Argument;
use think\console\input\Option;
use \app\common\model\BBTArtical;

\think\Loader::import('QueryList.vendor.autoload');
use QL\QueryList;

class BBTYuErXueqian extends Command
{
    protected function configure()
    {
        $this->setName('bbt_yuer_xueqian_spider')->setDescription('Grab baby tree parenting articles');
    }

    protected function execute(Input $input, Output $output)
    {
        # 1-2岁的宝宝称为幼儿期，共计12个月
        # https://m.babytree.com/week/weekly/xueqian_1_1;
        # https://m.babytree.com/week/weekly/xueqian_16_1;
    	
        if(!($url = $this->getUrl())){
            $output->writeln("16 levels has grabed");
            return ;
        }

        // 获取规则
        $rules = $this->getRules();
        // 获取数据
        $hj = QueryList::Query($url, $rules);
        $data = $hj->getData(function($x){
            return $x;
        });

        $month = $this->weekly*3;
        $year = floor($month/12);

        $max_month = intval($month - 12*$year);
        $max_month === 0 && $year--;
        $max_month = $max_month === 0 ? 12 : $max_month;
        $min_month = $max_month - 2;

        $artical_data = [
            'title' => $data[0]['title'],
            'artical' => $data[0]['articl'],
            'bbt_type' => 'yuer',               // 育儿
            'bbt_level' => 'xueqian',           // 学前
            'type_desc' => '学前期',            // 学前
            'year'  => (2+$year),
            'max'   => $max_month, 
            'min'   => $min_month, 
        ];

        BBTArtical::create($artical_data);

        $output->writeln('complete');
    }

    protected function getUrl() {

        $options = [
            // 缓存类型为File
            'type'   => 'File', 
             // 缓存有效期为永久有效
            'expire' => 0,
             // 指定缓存目录
            'path'   => CACHE_PATH . 'bbt/yuErXueqianEr/', 
        ];

        if(!($weekly = cache('weekly', '', $options))) {
            $weekly = 1;
        }

        if($weekly > 16) {
            return false;
        }

        $this->weekly = $weekly;

        cache('weekly', ($weekly+1), $options);

        $url = 'https://m.babytree.com/week/weekly/xueqian_%d_1';
        return $url = sprintf($url, $weekly);
    }

    protected function getRules() {
        return [
            "title"=>['.weekly-nav .title', 'text'],
            "articl"=>['.week-articl', 'html'],
        ];
    }
}
